ActionView::Base.field_error_proc = Proc.new do |html_tag, instance_tag|
  "<span class='field_error'>#{html_tag}</span>"
end

class ApplicationController < ActionController::Base
  helper :all
  helper_method :current_user, :logged_in?, :redirect_back_or_default
  filter_parameter_logging :password, :password_confirmation
  protect_from_forgery
  
  rescue_from 'Acl9::AccessDenied', :with => :access_denied
  
  protected
  
  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.record
  end
  
  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end
  
  def logged_in?
    current_user
  end
  
  def redirect_back_or_default(default)
    redirect_to(session[:return_to] || default)
    session[:return_to] = nil
  end
  
  private
  
  def store_target_location
    session[:return_to] = request.request_uri
  end
  
  def access_denied
    if logged_in?
      flash[:notice] = "You do not have permission to do that"
      redirect_to root_url
    else
      flash[:notice] = "You must be logged in to access this application"
      store_target_location
      redirect_to login_url
    end
  end
end
